﻿using LiWi;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static LiWi.Shell;

namespace HYTool
{
    public partial class HY : Form
    {
        Data data = new Data();
        public HY()
        {
            InitializeComponent();
            //查看是否有配方文件，无则创建初始值配方
            if (!File.Exists(data.file))
            {
                foreach (var item in com_recipeName.Items)
                {
                    data.SaveIni(item.ToString());
                }
            }
            //IP刷新
            comboBox_ipList.Items.Clear();
            byte[] ipList = new byte[512];
            Shell.PMC_SearchEthlist(ipList, 512, 200);
            string str = System.Text.ASCIIEncoding.Default.GetString(ipList);

            string[] ipArray = str.Split('\0');
            foreach (string item in ipArray)
            {
                if (item.Length > 0)
                {
                    comboBox_ipList.Items.Add(item);
                    comboBox_ipList.Text = item.ToString();
                }
            }
            //初始化参数
            panel4.Enabled = false;
            data_PosList.CellValidating += Data_PosList_CellValidating;
            btn_axisAdd.MouseDown += (sender, e) => { move(1); };
            btn_axisRed.MouseDown += (sender, e) => { move(-1); };
            btn_axisAdd.MouseUp += (sender, e) => { PMC_Single_Cancel(data.handle, 0, 2); };
            btn_axisRed.MouseUp += (sender, e) => { PMC_Single_Cancel(data.handle, 0, 2); };
        }

        private void Data_PosList_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.ColumnIndex == 1)
            {
                string inputValue = e.FormattedValue.ToString();
                if (!string.IsNullOrEmpty(inputValue))
                {
                    if (!decimal.TryParse(inputValue, NumberStyles.Float, CultureInfo.InvariantCulture, out _))
                    {
                        //如果不是数，提示错误
                        MessageBox.Show("请输入有效点位");
                        e.Cancel = true;
                    }
                }
            }
        }

        private void but_conControl_Click(object sender, EventArgs e)
        {
            if (data.handle == IntPtr.Zero)
            {
                
                PMC_OpenEth(comboBox_ipList.Text, ref data.handle);
                if (data.handle != IntPtr.Zero)
                {
                    but_conControl.Text = "断开";
                    panel4.Enabled = true;
                    //获取当前运行配方参数
                    PMC_GetUserVar(data.handle, "runRecipe", ref data.runRecipe);
                    com_recipeName.SelectedIndex=0;
                }
                else
                MessageBox.Show("连接失败，请检查IP或网关是否正确");
            }
            else
            {
                PMC_Rapidstop(data.handle, 2);
                PMC_Close(data.handle);
                data.handle = IntPtr.Zero;
                but_conControl.Text = "连接";
                panel4.Enabled = false;
            }

        }

        private void btn_AddPos_Click(object sender, EventArgs e)
        {
            float dpos = 0;
            string[] datas = new string[2];
            datas[0] = System.Convert.ToString(data_PosList.RowCount);
            PMC_GetDpos(data.handle, 0, ref dpos);
            datas[1] = System.Convert.ToString(dpos);
            data_PosList.Rows.Add(datas);
        }

        private void btn_delPos_Click(object sender, EventArgs e)
        {
            if (data_PosList.IsCurrentCellDirty)
                data_PosList.EndEdit();
            int rowCount = data_PosList.Rows.Count;
            if (rowCount > 0 && !data_PosList.AllowUserToAddRows)
                data_PosList.Rows.RemoveAt(data_PosList.Rows.Count - 1);
            else if (rowCount > 1)
                data_PosList.Rows.RemoveAt(data_PosList.Rows.Count - 2);
            else
                MessageBox.Show("没有可删除的行");
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                int numPos = data_PosList.Rows.Count - 1;
                if (numPos > 0)
                {
                    data.posList = new float[numPos];
                    int thisNum = 0;
                    //遍历获取设置点位
                    foreach (DataGridViewRow row in data_PosList.Rows)
                    {
                        //获取第二列的值
                        var cellValue = row.Cells[1].Value;
                        if (!row.IsNewRow)//检查是否有值
                        {
                            data.posList[thisNum] = (System.Convert.ToSingle(cellValue.ToString()));
                            thisNum++;
                        }
                    }
                    data.openSocket = check_openSocket.Checked == true ? 1 : 0;
                    //保存数据
                    data.SaveIni(com_recipeName.Text);
                    MessageBox.Show(com_recipeName.Text + "保存成功");
                }
                else
                {
                    MessageBox.Show("请输入有效点位");
                }


        }
            catch (ArgumentException mes)
            {
                MessageBox.Show($"保存失败，{mes.Message}");
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (data.handle != IntPtr.Zero)
            {
                byte aa = 0;
                int bb=0;
                bb=PMC_GetState(data.handle, ref aa);
                if (bb != 0)
                {
                    data.handle = IntPtr.Zero;
                    but_conControl.Text = "连接";
                    panel4.Enabled = false;
                }
                string posListString = "";
                float[] posList;
                float dpos = 0, iniPos = 0, speed = 0;
                int recipeNow = 0, posNum = 0;
                //点位更新
                PMC_GetDpos(data.handle, 0, ref dpos);
                lab_getPos.Text = dpos.ToString();
                //配方更新
                PMC_GetUserVar(data.handle, "runRecipe", ref recipeNow);
                lab_recipeNow.Text = $"配方{recipeNow}";
                //速度更新
                PMC_GetSpeed(data.handle, 0, ref speed);
                lab_speedNow.Text = speed.ToString();
                //取料位
                PMC_GetUserVar(data.handle, "iniPos", ref iniPos);
                lab_inidposNow.Text = $"{iniPos}";
                //运动点位
                PMC_GetUserVar(data.handle, "posNum", ref posNum);
                posList = new float[posNum];
                PMC_GetTable(data.handle, 1, posNum, posList);
                for (int i = 0; i < posNum; i++)
                {
                    posListString = posListString + $"点位{i+1}：{posList[i]}  ";
                    if ((i+1) % 3 == 0) posListString = posListString + "\r\n";
                }
                lab_dposListNow.Text = $"{posListString}";


                //限位，原点显示
                int In = 0;
                uint state = 0;
                PMC_GetFwdIn(data.handle, 0, ref In);
                PMC_GetIn(data.handle, In, ref state);
                if (state == 1)
                    lab_Fs.BackColor = Color.Green;
                else
                    lab_Fs.BackColor = Color.Gray;
                PMC_GetDatumIn(data.handle, 0, ref In);
                PMC_GetIn(data.handle, In, ref state);
                if (state == 1)
                    lab_Da.BackColor = Color.Green;
                else
                    lab_Da.BackColor = Color.Gray;
                PMC_GetRevIn(data.handle, 0, ref In);
                PMC_GetIn(data.handle, In, ref state);
                if (state == 1)
                    lab_Rs.BackColor = Color.Green;
                else
                    lab_Rs.BackColor = Color.Gray;
            }
        }

        private void btn_Load_Click(object sender, EventArgs e)
        {
            data.LoadIni(com_recipeName.Text);
            //更新窗口
            num_iniPos.Value = System.Convert.ToDecimal(data.iniPos);
            check_openSocket.Checked=data.openSocket==1?true: false;
            data_PosList.Rows.Clear();
            for (int i = 0; i < data.posList.Length; i++)
            {
                string[] datas = new string[2];
                datas[0] = System.Convert.ToString(data_PosList.RowCount);
                datas[1] = System.Convert.ToString(data.posList[i]);
                data_PosList.Rows.Add(datas);
            }
        }

        private void btn_Down_Click(object sender, EventArgs e)
        {
            PMC_Rapidstop(data.handle, 2);
            int a = -1;
            int numPos = data_PosList.Rows.Count - 1;
            if (numPos > 0)
            {
                data.posList = new float[numPos];
                int thisNum = 0;
                //遍历获取设置点位
                foreach (DataGridViewRow row in data_PosList.Rows)
                {
                    //获取第二列的值
                    var cellValue = row.Cells[1].Value;
                    if (!row.IsNewRow)//检查是否有值
                    {
                        data.posList[thisNum] = (System.Convert.ToSingle(cellValue.ToString()));
                        thisNum++;
                    }
                }
                data.openSocket = check_openSocket.Checked == true ? 1 : 0;
                a = PMC_SetTable(data.handle, 1, data.posList.Length, data.posList);
                a = PMC_SetUserVar(data.handle, "openSocket", data.openSocket);
                a = PMC_SetUserVar(data.handle, "posNum", data.posList.Length);
                a = PMC_SetUserVar(data.handle, "runRecipe", com_recipeName.SelectedIndex + 1);
                if (a == 0)
                {
                    //保存数据
                    data.SaveIni(com_recipeName.Text);
                    PMC_SetUserVar(data.handle, "runFlag", -2);
                    MessageBox.Show(com_recipeName.Text + "载入成功,请重新回原后使用");
                }
                if (a != 0)
                    MessageBox.Show("载入失败，检查控制卡连接情况");
            }else
            {
                MessageBox.Show("请输入有效点位");
            }
        }

        /// <summary>
        /// 轴运动
        /// </summary>
        /// <param name="mode">1：正向；-1：负向</param>
        private void move(int mode)
        {
            PMC_Single_Vmove(data.handle, 0, mode);
        }

        private void 荟义_FormClosing(object sender, FormClosingEventArgs e)
        {
            PMC_Rapidstop(data.handle, 2);
            PMC_Close(data.handle);
        }

        private void btn_iniState_Click(object sender, EventArgs e)
        {
            PMC_Single_Datum(data.handle, 0, 13);
        }
    }
}
